import React from 'react';

import {
  View,
  TouchableOpacity,
  TextInput,
  Text,
} from 'react-native';

import dismissKeyboard from 'dismissKeyboard';
import { CheckBox } from 'react-native-elements'

import BasePage from './BasePage';
import {StringUtils, TextUtils} from '../../utils/Utils';
import Config from '../../config';
import SizeUtils from '../../common/SizeUtils';
import ToastUtils from '../../common/ToastUtils';
import TPicker from '../../components/TPicker';


//公共输入文本
export default class CommonInputPage extends BasePage {
  constructor(props) {
    super(props);

    // this.props.pageData.routeData.default 默认文本 可不赋值
    // this.props.pageData.routeData.placeholder 文本框为空时显示的文本 可不赋值
    // this.props.pageData.routeData.editable 是否可编辑 可不赋值
    // this.props.pageData.routeData.length [min, max] 字符串长度 可不赋值
    // this.props.pageData.routeData.type 文本内容类型  email 邮件 default 文本 number 数字
    // this.props.pageData.routeData.callback 点击确定后回调的方法
    // this.props.pageData.routeData.title 顶部名字
    this._initData();
    this.state.mchecked=[];
  }

  render() {
    const isNoIput = this.props.pageData.routeData.type==="single"||this.props.pageData.routeData.type==='multi';
    return(
      <View style={{width:SizeUtils.getWindowSize().width, height:SizeUtils.getWindowSize().height,
          backgroundColor:"#ffffff"}}>
        {isNoIput?null:this._renderInput()}
        {this.props.pageData.routeData.type==="multi"?this._renderCheckbox():null}
        {this.props.pageData.routeData.type==="single"?this._renderCircleCheckbox():null}
        {this._renderNavigationBar()}
      </View>
    )
  }

  _initData() {
    console.log(this.props.pageData.routeData)
    this.state.content = this.props.pageData.routeData.default;
    if(this.state.content === null || this.state.content === undefined) {
      this.state.content = "";
    }
    this.state.contentheight = 0;
    this._maxLength = 999;
    if(this.props.pageData.routeData.length && this.props.pageData.routeData.length.length == 2) {
      this._maxLength = this.props.pageData.routeData.length[1];
    }
    this._minLength = 0
    if(this.props.pageData.routeData.length && this.props.pageData.routeData.length.length > 0) {
      this._minLength = this.props.pageData.routeData.length[0];
    }
    this._fields = this.props.pageData.routeData.fields||[];
  }

  _dealEnterPage() {
    this._initData();
  }

  _dealLeavePage() {
    this.setState({
      content:"",
      schecked:-1,
      mchecked:[],
    })
    dismissKeyboard();
  }
  _renderCircleCheckbox(){
    const that = this;
    return(
      <View style={{flex:1, paddingTop:Config.paddingTop, paddingLeft:SizeUtils.translateDesignWidthToCode(40),
          paddingRight:SizeUtils.translateDesignWidthToCode(40),}}>
          {that._fields.map((item,index)=>{
                return(
                  <CheckBox
                    containerStyle={{backgroundColor:'#00000000',borderColor:'#00000000'}}
                    key={index}
                    checkedIcon='dot-circle-o'
                    uncheckedIcon='circle-o'
                    title={item.name}
                    onPress={()=>{
                      that.setState({schecked:index});
                    }}
                    checked={that.state.schecked===index}
                  />)          
            })
          }
      </View>
    )
  }
  _renderCheckbox(){
    const that = this;
    return(
      <View style={{flex:1, paddingTop:Config.paddingTop, paddingLeft:SizeUtils.translateDesignWidthToCode(40),
          paddingRight:SizeUtils.translateDesignWidthToCode(40),}}>
          {
            that._fields.map((item,index)=>{
              return(
                  <CheckBox
                    containerStyle={{backgroundColor:'#00000000',borderColor:'#00000000'}}
                    key={index}
                    title={item.name}
                    onPress={()=>{
                      var list =that.state.mchecked;
                      if (list.indexOf(index)>=0) {
                        list.splice(list.indexOf(index),1)
                      }else{
                        list.push(index)
                      }
                      that.setState({
                        mchecked: list
                      });
                    }}
                    checked={that.state.mchecked.indexOf(index)>=0}
                  />
              )
            })
          }
      </View>
    )
  }

//keyboardType enum("default", 'numeric', 'email-address', "ascii-capable", 'numbers-and-punctuation', 'url', 'number-pad', 'phone-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search')
  _renderInput() {
    return(
      <View style={{flex:1, paddingTop:Config.paddingTop, paddingLeft:SizeUtils.translateDesignWidthToCode(40),
          paddingRight:SizeUtils.translateDesignWidthToCode(40),}}>
        <TextInput
          style={{height: Math.max(SizeUtils.translateDesignHeightToCode(800), this.state.contentheight),
            borderColor: 'gray', borderWidth: 0,
            marginTop: SizeUtils.translateDesignHeightToCode(20),
             textAlignVertical: "top", fontSize: SizeUtils.translateFontSizeToCode(30)}}
          onChangeText = {(content) => this.setState({content})}
          placeholder = {this._getInputDefaultText()}
          multiline = {true}
          underlineColorAndroid="transparent"
          value = {this.state.content}
          onContentSizeChange={this._onContentSizeChange.bind(this)}
          maxLength={this._maxLength}
          underlineColorAndroid="transparent"
          returnKeyType = "default"
          // onSubmitEditing = {() => this._doSubmit()}
          // blurOnSubmit={true}
          enablesReturnKeyAutomatically={true}
          editable={!(this.props.pageData.routeData.editable === false)}
          keyboardType={this._getKeyborderType()}
        />
      </View>
    )
  }

  _getKeyborderType() {
    if (this.props.pageData.routeData.type == "number") {
      return "numeric";
    }
    else if (this.props.pageData.routeData.type == "email") {
      return "email-address";
    }
    return "default";
  }

  _getInputDefaultText() {
    let text = "";
    if(this.props.pageData.routeData.editable === false) {
      text = "";
    }
    else if (this.props.pageData.routeData.placeholder) {
      text = this.props.pageData.routeData.placeholder;
    }
    else {
      text = "请输入(";
      if(this._minLength === this._maxLength) {
        text += this._minLength;
      }
      else {
        text += this._minLength + "-" + this._maxLength;
      }
      text += "个";
      if(this.props.pageData.routeData.type == "number") {
        text += "数字";
      }
      else {
        text += "中文或者英文";
      }
      text += ")";
    }
    return text;
  }

  _onContentSizeChange(event) {
    this.setState({contentheight: event.nativeEvent.contentSize.height + SizeUtils.translateDesignHeightToCode(80)});
  }

  _getTitle() {
    return this.props.pageData.routeData.title;
  }

  _onPressNavigationBarRightBtn() {//点击保存
    if(this.props.pageData.routeData.editable === false) {
      return;
    }
    const isNoIput = this.props.pageData.routeData.type==="single"||this.props.pageData.routeData.type==='multi';
    if (isNoIput) {
      if (this.props.pageData.routeData.type==="single") {
        if (this.state.schecked<0) {
          ToastUtils.show('请选择一个值');
          return;
        }
        this.props.pageData.routeData.callback(this._fields[this.state.schecked].name);
        this.goBack();
      }
      if (this.props.pageData.routeData.type==="multi") {
        if (this.state.mchecked.length<=0) {
          ToastUtils.show('请选择一个值');
          return;
        }
        var str = '';
        for (var i = 0; i < this.state.mchecked.length; i++) {
          const index =this.state.mchecked[i];
          if (str.length>0) {
            str+=',';
          }
          str+=this._fields[index].name;
        }
        this.props.pageData.routeData.callback(str);
        this.goBack();
      }
    }else{
      let contentLength = this.state.content.length;
      if(contentLength >= this._minLength && contentLength <= this._maxLength) {
        this._doSubmit();
      }
      else {
        ToastUtils.show(this._getToastText());
      }
    } 
  }

  _getToastText() {
    let text = "文本长度不符合(";
    if(this._minLength === this._maxLength) {
      text += this._minLength;
    }
    else {
      text += this._minLength + "-" + this._maxLength;
    }
    text += "个";
    if(this.props.pageData.routeData.type == "number") {
      text += "数字";
    }
    else {
      text += "中文或者英文";
    }
    text += ")";
    return text;
  }

  _renderNavigationBarRightButtonContent() {
    if(this.props.pageData.routeData.editable === false) {

    }
    else {
      return super._renderNavigationBarRightButtonContent();
    }
  }

  _doSubmit() {
    if(this.props.pageData.routeData.type == "email" && !TextUtils.isEmail(this.state.content)) {
      ToastUtils.show("邮件格式不对");
    }
    else {
      this.props.pageData.routeData.callback(this.state.content);
      this.goBack();
    }
  }
}
